package com.tianji.promotion.service.impl;

import com.tianji.common.utils.ObjectUtils;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constans.PromotionConstants.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-20
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private BoundValueOperations<String, String> serialops;
    public ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate) {
        this.serialops = redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }

    @Override
    public void asyncGenerateCode(Coupon coupon) {
        Integer totalNum = coupon.getTotalNum();
        // 获取当前序列号
        Long serialNum = serialops.increment(totalNum);
        Integer id = serialNum.intValue();
        if(ObjectUtils.isEmpty(id)){
            return;
        }
        Integer max = serialNum.intValue();
        List<ExchangeCode> list = new ArrayList<>();
        for (Integer i = max-totalNum+1; i <= serialNum; i++) {
                // 生成兑换码
                String code = CodeUtil.generateCode(i, coupon.getId());
                //保存到数据库
                ExchangeCode e = new ExchangeCode();
                e.setCode(code);
                e.setId(i);
                e.setExchangeTargetId(coupon.getId());
                e.setExpiredTime(coupon.getIssueEndTime());
                list.add(e);
        }
        this.saveBatch(list);
        //无敌的我又迷路了
        //我又无敌了
    }
}
